const { server } = require('../config')
const { HttpException } = require('../core/http-exception')

const exception = (ctx, err) => {
  const isDev = server.environment === 'dev'
  const isHttpException = err instanceof HttpException
  if (isDev && !isHttpException) {
    throw err
  }

  if (isHttpException) {
    ctx.body = {
      msg: err.msg,
      code: err.errorCode
    }
    ctx.response.status = err.code
  } else {
    ctx.body = {
      msg: '未知错误',
      code: 9999
    }
    ctx.response.status = 500
    console.error(`API服务错误：${err}`);
  }
}

module.exports = exception;